package com.lahuan.rpc.protocol.netty.server;

import com.lahuan.rpc.protocol.tcp.RpcfxRequest;
import com.lahuan.rpc.protocol.tcp.RpcfxResponse;
import org.apache.dubbo.common.URL;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ServerInvoker<T> {

    private final T impl;
    private final Class<T> type;

    public ServerInvoker(T impl, Class<T> type){
        this.impl = impl;
        this.type = type;
    }

    public RpcfxResponse invoke(RpcfxRequest request) throws ClassNotFoundException {
        RpcfxResponse response = new RpcfxResponse();
        try {
            Method method = resolveMethodFromClass(type, request.getMethod());
            Object result = method.invoke(impl, request.getParams());
            response.setResult(result);
            response.setStatus(true);
            return response;
        } catch ( IllegalAccessException | InvocationTargetException e) {

            // 客户端也需要判断异常
            e.printStackTrace();
            response.setException(e);
            response.setStatus(false);
            return response;
        }
    }

    private Method resolveMethodFromClass(Class<?> klass, String methodName) {
       try {
           Method[] methods = klass.getMethods();
           return Arrays.stream(methods).filter(m -> methodName.equals(m.getName())).findFirst().get();
       }catch (Exception ex){
           ex.printStackTrace();
       }
        return null;
    }

}
